package misc

import (
	"dhfshop/controllers/base"
	"dhfshop/models/misc"
	"github.com/astaxie/beego/validation"
	"strconv"
	"time"
)

type ShopConfigController struct {
	base.BaseController
}

func (this *ShopConfigController) List() {
	query, _, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	l, cnt, err := misc.GetAllShopConfigs(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount int64              `json:"total_count"`
		ShopConfig []*misc.ShopConfig `json:"shopconfigs"`
	}{TotalCount: cnt, ShopConfig: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *ShopConfigController) Post() {
	var v misc.ShopConfig
	valid := validation.Validation{}
	this.ParseForm(&v)
	v.CompanyId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v.UserId = int64(this.Ctx.Input.GetData("curUserId").(int))
	valid.Required(v.Field, "field")
	valid.Required(v.Value, "value")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	id, err := misc.AddShopConfig(&v)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		ShopConfigId int64     `json:"shop_config_id"`
		Created      time.Time `json:"created"`
	}{ShopConfigId: id, Created: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ShopConfigController) Put() {
	v := misc.ShopConfig{}
	this.ParseForm(&v)
	v.CompanyId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{""})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		if err := misc.UpdateShopConfigById(&v, updateFields...); err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		ShopConfigId int64     `json:"shop_config_id"`
		Modified     time.Time `json:"modified"`
	}{ShopConfigId: v.ShopConfigId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ShopConfigController) Delete() {
	tidStr := this.GetString("shop_config_id")
	shop_config_id, _ := strconv.ParseInt(tidStr, 10, 0)
	if err := misc.DeleteShopConfig(shop_config_id); err != nil {
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		ShopConfigId int64     `json:"shop_config_id"`
		Modified     time.Time `json:"modified"`
	}{ShopConfigId: shop_config_id, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
